<template>

  <!--    跳转声明 类似router-link 直接把vue页放在pages目录下即可-->
  <!--    <nuxt-link to="/">首页</nuxt-link>-->
  <!--    <nuxt-link to="/user">用户</nuxt-link>-->
  <!--    <nuxt-link to="/login">登录</nuxt-link>-->
  <!--    nuxt标签就等同于路由点位符router-view-->


  <el-container style="height: 100%">
    <!--        <div class="loading-wrapper">-->
    <!--          <Loading  v-show="showLoading"></Loading>-->
    <!--        </div>-->
    <el-header class="header">
      <el-menu mode="horizontal" class="el-menu-demo" background-color="#545c64"
               text-color="#fff"
               active-text-color="#ffd04b"
               @select="handleSelect"
               :router="true"
               :default-active="$route.path">
        <el-menu-item index="/home">主页</el-menu-item>
        <el-submenu index="2">
          <template slot="title">运维资料</template>
          <el-menu-item index="/device">资产清单</el-menu-item>
          <!--          <el-menu-item index="/soft">软件资产</el-menu-item>-->
          <el-menu-item index="/iptable">IP地址表</el-menu-item>
          <el-menu-item index="/tops">拓扑图</el-menu-item>
          <!--          <el-menu-item index="/pwtable">密码资料</el-menu-item>-->
          <!--          <el-submenu index="2-4">-->
          <!--            <template slot="title">选项4</template>-->
          <!--            <el-menu-item index="2-4-1">选项1</el-menu-item>-->
          <!--            <el-menu-item index="2-4-2">选项2</el-menu-item>-->
          <!--            <el-menu-item index="2-4-3">选项3</el-menu-item>-->
          <!--          </el-submenu>-->
        </el-submenu>
        <el-menu-item index="/files">文件管理</el-menu-item>
        <el-menu-item index="/remote_connect">远程连接</el-menu-item>

        <!--        <el-menu-item index=""><a href="/files">文件管理</a></el-menu-item>-->

        <!--          <el-menu-item index=""><a href="https://www.ele.me" target="_blank">订单管理</a></el-menu-item>-->

<!--        <el-tag type="danger" style="font-weight: bolder">试用版！</el-tag>-->
        <div style="color: white;float: right;margin-right: 20px">
          <el-button v-if="this.$store.state.user.err !== 0" size="mini" @click="$router.push('/login')">登录
          </el-button>
          <span v-else>
              <span>{{`${this.$store.state.user.data.result.userName}`}}</span>
              <el-dropdown>
            <el-button size="mini" type="info" icon="el-icon-s-custom" circle></el-button>

            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="changePw"><i class="el-icon-key"></i>更改密码</el-dropdown-item>
              <el-dropdown-item v-if="this.$store.state.user.data.result.rank==1" @click.native="manageHost"><i
                class="el-icon-s-platform"></i>信任主机</el-dropdown-item>
              <el-dropdown-item v-if="this.$store.state.user.data.result.rank==1" @click.native="manageUsers"><i
                class="el-icon-s-custom"></i>用户管理</el-dropdown-item>
              <el-dropdown-item @click.native="out"><i class="el-icon-switch-button"></i>退出登录</el-dropdown-item>
            </el-dropdown-menu>
                <!--                <span v-text="a" id="a">   </span>-->
          </el-dropdown>
          </span>

        </div>

      </el-menu>
      <!--        修改密码弹框-->
      <el-dialog title="修改密码" :visible.sync="dialogVisible">
        <el-form :model="user_Form" :rules="userFormRules" ref="user_Form">
          <el-form-item prop="oldPassword" label="当前密码：" label-width="100px">
            <el-input type="password" v-model="user_Form.oldPassword" placeholder="输入当前密码" show-password
                      clearable></el-input>
          </el-form-item>
          <el-form-item prop="newPassword" label="新密码：" label-width="100px">
            <el-input type="password" v-model="user_Form.newPassword" placeholder="输入新密码" show-password
                      clearable></el-input>
          </el-form-item>
          <el-form-item prop="newPassword1" label="新密码：" label-width="100px">
            <el-input type="password" v-model="user_Form.newPassword1" placeholder="再一次输入新密码" show-password
                      clearable></el-input>
          </el-form-item>
        </el-form>
        <el-row type="flex" justify="center" :gutter="20" style="margin:20px 0 40px 0; ">
          <el-col :span="3" style="margin-right: 10px">
            <el-button type="primary" @click="submitUser">提 交</el-button>
          </el-col>
          <el-col :span="3" style="margin-left: 10px">
            <el-button type="info" @click="dialogVisible=false">取 消</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <!--        信任主机弹框-->
      <el-dialog id="hostDialog" style="padding: 0" title="管理主机列表" :visible.sync="hostDialogVisible">
        <el-table :data="hostList">
          <el-table-column type="index" width="70" label="序号"></el-table-column>
          <el-table-column label="信任IP" prop="host"></el-table-column>
          <el-table-column label="备注信息" prop="beizhu"></el-table-column>
          <el-table-column label="操作" width="120">
            <template slot-scope="scope">
              <el-popconfirm v-if="!scope.row.default" title="确定删除吗？" @confirm="deleteHost(scope.row,scope.$index)">
                <el-button type="danger" icon="el-icon-delete" slot="reference" size="mini"
                           onClick="event.cancelBubble = true"></el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-form v-show="addHostVisible" :inline="true" :model="hostForm" :rules="hostFormRules" ref="hostForm"
                 style="margin-top: 20px">
          <el-form-item label="主机IP：" prop="host">
            <el-input v-model="hostForm.host" placeholder="0.0.0.0代表所有IP" clearable></el-input>
          </el-form-item>
          <el-form-item label="备注：">
            <el-input v-model="hostForm.beizhu" placeholder="备注"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-circle-check" size="mini" @click="submitHost">提交</el-button>
          </el-form-item>
        </el-form>
        <el-button v-if="addHostButton" type="success" icon="el-icon-circle-plus-outline" size="mini"
                   @click="addHost()">新 增
        </el-button>
      </el-dialog>
      <!--        用户管理弹框-->
      <el-dialog class="blueDialog" style="padding: 0" title="用户列表" :visible.sync="userDialogVisible">
        <view_user ref="view_user"></view_user>
      </el-dialog>
    </el-header>

    <el-main>
      <el-breadcrumb separator="/" style="margin-bottom: 5px">
        <el-breadcrumb-item to="/home">主页</el-breadcrumb-item>
        <el-breadcrumb-item v-for="(item,index) in routerData" :key="index" :to="item.path">
          {{item.meta.title||item.name}}
        </el-breadcrumb-item>
      </el-breadcrumb>
      <nuxt v-if="isRouterAlive"/>
    </el-main>
    <el-footer>
      <span style="font-size: small;color: white">Copyright 2021-2031 &nbsp;&nbsp; 当前版本：v3.0 &nbsp;&nbsp;版权所有：湖南三体星信息技术有限公司 &nbsp;&nbsp;联系电话:18674824512</span>&nbsp;&nbsp;
      <el-link href="/about" type="primary" target="_blank"><span style="font-size: small">关于我们</span></el-link>
    </el-footer>
  </el-container>


</template>
<script>
  //import Loading from '~/components/loading.vue'
  import view_user from '~/components/user.vue';
  import md5 from 'js-md5'
  // 验证IP的正则
  let ip_reg = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
  export default {
    components: {view_user},
    // components: {Loading},
    //middleware:'auth',//定义中间件
    // middleware(){
    //   console.log("层级中件间")
    // }
    created: function () {
      //查验一下token是否还在有效期
      // const res = await this.$axios.post('/api/login', this.loginForm);
    },
    computed: {},
    data() {
      return {
        // showLoading: true,
        user_Form: {newPassword: '', newPassword1: '', oldPassword: ''},
        userFormRules: {
          oldPassword: [{required: true, message: '输入不能为空', trigger: 'blur',},],
          newPassword: [{required: true, message: '输入不能为空', trigger: 'blur',},],
          newPassword1: [{required: true, message: '输入不能为空', trigger: 'blur',}, {validator: this.chkpw,},],
        },
        hostFormRules: {
          host: [{required: true, message: '输入不能为空', trigger: 'blur',}, {
            pattern: ip_reg,
            message: 'IP地址格式不正确',
            trigger: 'blur',
          }]
        },
        routerData: [],
        hostList: [],
        activeIndex: '/home',
        hostForm: {},
        username: '未登录',
        isRouterAlive: true,
        dialogVisible: false,
        addHostVisible: false,
        hostDialogVisible: false,
        userDialogVisible: false,
        addHostButton: true,
      }
    },
    mounted() {
      this.routerData = this.$route.matched;
    },
    methods: {
      async manageHost() {
        this.addHostVisible = false
        this.addHostButton = true
        const res = await this.$axios.get('/api/hosts')
        this.hostList = res.data.result
        //console.log(this.hostList)

        //this.hostList.unshift({host:'192'})
        this.hostDialogVisible = true;
      },
      addHost() {
        this.hostForm = {}
        this.addHostVisible = true
        this.addHostButton = false
        console.log(this.addHostVisible)
        //this.$nextTick()
      },
      async deleteHost(row, index) {
        const res = await this.$axios.delete('/api/hosts/' + row._id)
        if (res.status == 200 && res.data.code == "success") {
          this.$message.info('已删除')
          this.hostList.splice(index, 1)
        }
      },
      submitHost() {
        this.$refs.hostForm.validate(async valid => {
          if (valid) {
            const res = await this.$axios.post('/api/hosts', this.hostForm)
            if (res.status == 200 && res.data.code == "success") {
              this.$message.success('提交成功')
              this.hostList.push(res.data.result)
              this.addHostVisible = false
              this.addHostButton = true
              return
            }
            this.$message.error('提交失败')
          }
        })


      },
      changePw() {
        this.dialogVisible = true;

      },
      submitUser() {
        this.$refs.user_Form.validate(
          async valid => {
            if (valid) {
              let form = JSON.parse(JSON.stringify(this.user_Form))
              form.oldPassword = md5(md5(form.oldPassword) + 'liu008')
              form.newPassword = md5(md5(form.newPassword) + 'liu008')
              form.userId = this.$store.state.user.data.result.userId
              const res = await this.$axios.post('/api/user/changepw', form)
              if (res.data.result == 'error') {
                this.$message.error('当前密码不正确')
              } else if (res.data.result.username) {
                this.$message.success('修改成功！')
                this.dialogVisible = false
              }
            }
          }
        )
      },
      chkpw(rule, value, callback) {
        if (value != null && value != "") {
          if (this.user_Form.newPassword != value) {
            return callback(new Error('与上面的输入密码不一致'))
          }
          return callback()
          // //检查是否是数字形式
          // if (value >= 0 && value <= 32) return callback()
          // if (mask_reg.test(value)) return callback()
          // callback(new Error('您输入的掩码格式不正确!'))
        }
      },
      // handleSelect(key, keyPath) {
      //   //console.log(this.$router)
      //   this.$router.push(key)
      //   // console.log(key, keyPath)
      // },
      handleSelect(index) {
        this.activeIndex = index
        // if (index === this.$route.path) {
        //   this.reload()
        // }
      },
      reload() {
        this.isRouterAlive = false
        this.$nextTick(function () {
          this.isRouterAlive = true
        })
      },
      out() {
        //删除cookie和vue
        this.$cookies.removeAll();
        this.$store.commit('user/M_UPDATE_USER', {err: 1, msg: '退出登录', token: null, data: null})
        this.$router.push('/')
        this.$message('已退出登录')
        //location.reload();
      },
      manageUsers() {
        this.userDialogVisible = true
        this.$nextTick(() => {
          this.$refs.view_user.getUsers()
        });
      },

    },
    watch: {
      $route() {
        this.handleSelect(this.activeIndex);
        this.routerData = this.$route.matched;
      }
    }
  }
</script>
<style lang="less">
  .header {
    /deep/ .el-dialog__wrapper {
      .el-dialog {
        .el-dialog__header {
          background: #409EFF;
          color: white;
          line-height: initial;
        }

        .el-dialog__title {
          color: white;
          font-weight: bold;
        }

        .el-dialog__close {
          color: white;
        }

        .el-form {
          .el-form-item__cont {
            flex: 1;
          }
        }

      }
    }
  }

  .el-form--inline .el-form-item__label {
    float: left;
  }

  #hostDialog {
    .el-dialog__body {
      padding-top: 0px;
    }
  }

  .blueDialog {
    .el-dialog__header {
      background: #409EFF;
      color: white;
      padding: 0;
    }

    .el-dialog__title {
      color: white;
      font-weight: bold;
    }

    .el-dialog__close {
      color: white;
    }

    .el-dialog__body {
      padding-top: 10px;
    }
  }
  .blueDialog1 {
    .el-dialog__header {
      background: #409EFF;
      color: white;
    }

    .el-dialog__title {
      color: white;
      font-weight: bold;
    }

    .el-dialog__close {
      color: white;
    }

    .el-dialog__body {
      padding-top: 10px;
    }
  }

  .el-main {
    background-color: #E9EEF3;
    color: #333;
    text-align: center;
  }

  .el-header, .el-footer {
    padding: 0;
    background-color: #B3C0D1;
    color: #333;
    text-align: center;
    line-height: 60px;
  }

  html, body, #__nuxt, #__layout {
    height: 100%;
    margin: 0;
    padding: 0;
    font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
  }

  *,
  *:before,
  *:after {
    box-sizing: border-box;
    margin: 0;
  }

  .button--green {
    display: inline-block;
    border-radius: 4px;
    border: 1px solid #3b8070;
    color: #3b8070;
    text-decoration: none;
    padding: 10px 30px;
  }

  .button--green:hover {
    color: #fff;
    background-color: #3b8070;
  }

  .button--grey {
    display: inline-block;
    border-radius: 4px;
    border: 1px solid #35495e;
    color: #35495e;
    text-decoration: none;
    padding: 10px 30px;
    margin-left: 15px;
  }

  .button--grey:hover {
    color: #fff;
    background-color: #35495e;
  }

</style>
